package jmf;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class Reproductor extends Thread
{
	private static final int	EXTERNAL_BUFFER_SIZE = 5000;
	private File file;
	SourceDataLine	line = null;
	AudioInputStream	audioInputStream = null;
	boolean detener = false;

	public void setFile(File file){
		this.file = file;
	}

	public void run()
	{
		reproducir();
	}
	
	public Reproductor(File archivo) {
		this.file = archivo;
	}
	
	public void detener(){
		detener = true;
	}
	
	public void reproducir(){
		File	soundFile = this.file;
		try
		{
			audioInputStream = AudioSystem.getAudioInputStream(soundFile);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(1);
		}

		AudioFormat	audioFormat = audioInputStream.getFormat();
		DataLine.Info	info = new DataLine.Info(SourceDataLine.class,
												 audioFormat);
				
		try
		{
			line = (SourceDataLine) AudioSystem.getLine(info);
			line.open(audioFormat);
		}
		catch (LineUnavailableException e)
		{
			e.printStackTrace();
			System.exit(1);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(1);
		}
		line.start();

		int	nBytesRead = 0;
		byte[]	abData = new byte[EXTERNAL_BUFFER_SIZE];
		while (nBytesRead != -1 && !detener)
		{
			try
			{
				nBytesRead = audioInputStream.read(abData, 0, abData.length);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			if (nBytesRead >= 0)
			{
				line.write(abData, 0, nBytesRead);
			}
		}
		line.drain();
		line.close();
		try {
			audioInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
